
<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">系统登录</h2>
      <el-form 
        :model="loginForm" 
        :rules="rules" 
        ref="loginFormRef"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleLogin"
            :loading="loading"
            class="login-btn"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ref } from 'vue'
import router from '@/router'

interface LoginForm {
  username: string
  password: string
}

const route = useRoute()
const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const loginForm = ref<LoginForm>({
  username: '',
  password: ''
})

const rules = ref<FormRules<LoginForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '长度在3到12个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在6到16个字符', trigger: 'blur' }
  ]
})

const handleLogin = async () => {
  try {
    await loginFormRef.value?.validate()
    loading.value = true
    // 这里替换为实际登录API调用
    console.log('登录信息:', loginForm.value)
    ElMessage.success('登录成功')
    useAuthStore().login("1231231231");
    console.log(useAuthStore().$state.token)
    const target = isStringParam(route.query.redirect) 
                    ? route.query.redirect 
                    : '/'
    router.push(target) // 优先跳转来源页
  } catch (error) {
    console.error('验证失败:', error)
  } finally {
    loading.value = false
  }
}

function isStringParam(param: unknown): param is string {
  return typeof param === 'string'
}



</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}
.login-card {
  width: 400px;
  padding: 20px;
}
.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
}
.login-btn {
  width: 100%;
}
</style>
